<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between" style="margin-bottom: 20px">
        <el-col :span="6"><span style="font-size: large">快速查询</span></el-col>
      </el-row>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="110px">
        <el-form-item label="单据号">
          <el-input v-model="queryParams.billsID" placeholder="请输入单据号" clearable></el-input>
        </el-form-item>
        <el-form-item label="单据类型">
          <el-input v-model="queryParams.billsType" placeholder="请输入单据类型" clearable></el-input>
        </el-form-item>
        <el-form-item label="往来单位">
          <el-input v-model="queryParams.billsCD" placeholder="请输入往来单位" clearable></el-input>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="queryParams.timeList"
            format="yyyy-MM-dd hh:mm:ss"
            value-format="yyyy-MM-dd hh:mm:ss"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="margin-left: 45px">
          <el-button type="primary" icon="el-icon-search" @click="queryFinishedProductsList">查询</el-button>
          <el-button type="danger" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">出库单据明细</span></el-col>
      </el-row>

      <div class="table-wrapper">
        <el-table
          :data="detailList"
          border
          height="100%"
          ref="tableRef"
          style="width: 100%"
          :key="tableKey">
          <!-- 动态渲染可见列 -->
          <el-table-column
            show-overflow-tooltip
            v-for="column in visibleColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            align="center"
            :width="column.width"/>

          <!-- 固定右侧操作列 + 下拉选择列 -->
          <el-table-column width="100" align="center" fixed="right">
            <template #header>
              <el-dropdown
                ref="dropdownRef"
                trigger="click"
                placement="bottom"
                :hide-on-click="false"
                @visible-change="handleDropdownVisibleChange">
                <span class="el-dropdown-link">
                  列表筛选<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="column-select-dropdown">
                  <el-dropdown-item>
                    <el-checkbox-group
                      v-model="selectedColumns"
                      @change="handleColumnChange">
                      <div v-for="column in allColumns" :key="column.prop" class="column-item">
                        <el-checkbox :label="column.prop">{{ column.label }}</el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="block" style="float: right; margin: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[100,150,200,500]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"/>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  selectBillsDetailList
} from '@/api/storeM/yxl.js';

export default {
  data() {
    return {
      tableKey: 0, // 用于强制重新渲染表格
      pageNum: 1,
      pageSize: 100,
      total: 0,
      detailList: [],
      queryParams: {
        billsID: '',
        billsType: '',
        billsCD: '',
        timeList:[]
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      refreshTimer: null, // 定时器
      refreshInterval: 300000,// 5分钟刷新一次，可根据需求调整
      allColumns: [{
        prop: 'CheckDate',
        label: '日期',
        width: 160
      },
        {
          prop: 'BillsID',
          label: '通知单编号',
          width: 160
        },
        {
          prop: 'unit_code',
          label: '货位名称',
          width: 160
        },
        {
          prop: 'customer_code',
          label: '客户编码',
          width: 160
        },
        {
          prop: 'customer_name',
          label: '客户名称',
          width: ''
        },
        {
          prop: 'product_code',
          label: '药品编码',
          width: 100
        },
        {
          prop: 'product_name',
          label: '药品名称',
          width: 100
        },
        {
          prop: 'DrugGG',
          label: '商品规格',
          width: 100
        },
        {
          prop: 'DrugDW',
          label: '单位',
          width: 80
        },
        {
          prop: 'DrugCD',
          label: '生产厂家',
          width: ''
        },
        {
          prop: 'DrugBatchNo',
          label: '批号',
          width: 100
        },
        {
          prop: 'DrugPD',
          label: '生产日期',
          width: ''
        },
        {
          prop: 'DrugCheckNum',
          label: '数量',
          width: 80
        },
        {
          prop: 'price',
          label: '单价',
          width: 80
        },
        {
          prop: 'jixing',
          label: '剂型',
          width: ''
        },
        {
          prop: 'stu_class',
          label: '类别',
          width: 80
        },
        {
          prop: 'approval_num',
          label: '批准文号',
          width: 120
        },
        {
          prop: 'bar_code',
          label: '商品条码',
          width: ''
        },
      ],
      selectedColumns: [
        'CheckDate', 'BillsID', 'unit_code', 'customer_code', 'customer_name',
        'product_code', 'product_name', 'DrugGG', 'DrugDW', 'DrugCD', 'DrugBatchNo',
        'DrugPD', 'DrugCheckNum', 'price', 'jixing', 'stu_class',
        'approval_num', 'bar_code'
      ]
    };
  },
  computed: {
    visibleColumns() {
      return this.allColumns.filter(column => this.selectedColumns.includes(column.prop));
    }
  },
  created() {
    this.queryFinishedProductsList();
    this.startAutoRefresh();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
  },
  methods: {
    // 启动自动刷新
    startAutoRefresh() {
      this.stopAutoRefresh(); // 先停止已有的定时器
      this.refreshTimer = setInterval(() => {
        this.queryFinishedProductsList();
      }, this.refreshInterval);
    },
    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    // 处理列选择变化
    handleColumnChange() {
      this.tableKey = Math.random(); // 强制重新渲染表格
      this.$nextTick(() => {
        this.$refs.tableRef?.doLayout?.();
      });
    },
    // 处理下拉菜单可见性变化
    handleDropdownVisibleChange(visible) {
      if (!visible) {
        this.$nextTick(() => {
          this.$refs.tableRef?.doLayout?.();
        });
      }
    },
    // 查询数据
    queryFinishedProductsList() {
      const [startDate , endDate] = Array.isArray(this.queryParams.timeList) &&
      this.queryParams.timeList.length === 2 ?
        this.queryParams.timeList : [null, null];
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...this.queryParams,
        startDate,
        endDate
      };
      selectBillsDetailList(params).then(res => {
        this.detailList = res.data.data.rows;
        this.total = res.data.data.total;

        // 如果 dropdown 打开了，重新拉数据时强制关闭
        this.$refs.dropdownRef?.hide?.();

        // 数据加载后重新计算表格布局
        this.$nextTick(() => {
          this.$refs.tableRef?.doLayout?.();
        });
      });
    },
    // 处理分页大小变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.pageNum = 1;
      this.queryFinishedProductsList();
    },
    // 处理当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.queryFinishedProductsList();
    },
    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        billsID: '',
        billsType: '',
        billsCD: '',
        timeList: []
      };
      this.queryFinishedProductsList();
    },
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

.el-card {
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.table-wrapper {
  overflow-x: auto;
  height: calc(100vh - 320px);
  width: 100%;
  position: relative;
}

.el-table {
  width: 100% !important;
  table-layout: fixed;
}

.el-table__fixed-right {
  height: 100% !important;
  right: 0 !important;
}

.el-table__header-wrapper {
  z-index: 2;
}

.el-dropdown-link {
  cursor: pointer;
  color: rgb(81, 90, 110);
  display: flex;
  align-items: center;
}

.el-dropdown-link:hover {
  color: #409EFF;
}

.column-select-dropdown {
  padding: 10px;
  max-height: 400px;
  overflow-y: auto;
  z-index: 9999 !important;
}

.column-item {
  padding: 5px 10px;
  min-width: 150px;
  white-space: nowrap;
}

.el-dropdown-menu__item {
  padding: 0;
}

.el-pagination {
  margin-top: 15px;
}

.mt20 {
  margin-top: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
